import request from '@/utils/request'
import type { ApiResponse, ConfigItem } from './types'

/**
 * 获取所有配置（带分页）
 * @param page 页码，默认为1
 * @param limit 每页数量，默认为10
 */
export const getAllConfigs = (page: number = 1, limit: number = 10): Promise<ApiResponse<ConfigItem[]>> => {
  return request.get({
    url: '/config',
    params: {
      page,
      limit,
    },
  })
}

/**
 * 根据键获取配置
 */
export const getConfigByKey = (key: string): Promise<ApiResponse<ConfigItem>> => {
  return request.get({
    url: `/config/${key}`,
  })
}

/**
 * 批量获取配置
 */
export const getConfigsByKeys = (keys: string[]): Promise<ApiResponse<ConfigItem[]>> => {
  return request.get({
    url: '/config/batch/get',
    params: {
      keys: keys.join(','),
    },
  })
}

/**
 * 创建配置
 */
export const createConfig = (
  key: string,
  value: any,
  options?: Partial<ConfigItem>,
): Promise<ApiResponse<ConfigItem>> => {
  return request.post({
    url: '/config/create',
    data: {
      key,
      value,
      options,
    },
  })
}

/**
 * 更新配置
 */
export const updateConfigByKey = (
  key: string,
  value: any,
  options?: Partial<ConfigItem>,
): Promise<ApiResponse<ConfigItem>> => {
  return request.post({
    url: '/config/update',
    data: {
      key,
      value,
      options,
    },
  })
}

/**
 * 设置配置（存在则更新，不存在则创建）
 * @deprecated 请使用 createConfig 或 updateConfigByKey 函数
 */
export const setConfig = (key: string, value: any, options?: Partial<ConfigItem>): Promise<ApiResponse<ConfigItem>> => {
  return request.post({
    url: '/config/set',
    data: {
      key,
      value,
      options,
    },
  })
}
